import os
from django.http import JsonResponse
from common.error import *
from news import TtoV
from news import makeChartText
import json
import time
import requests
from mainapp.models import TChart
from pymongo import MongoClient
import random

client = MongoClient('mongodb://127.0.0.1:27017/')  # 本地
db = client['match']
collection1 = db['basicmatchdetail']
collection2 = db['playeraveragedata']
collection3 = db['hupuidtonbaid']
# 测试用路径

server_path = "http://127.0.0.1:8089/api/task/"


# F:\\program doc\\林强 新闻网站\\chuanmei_news-kong_dev\\chuanmei_news-kong_dev\\news_server\\media\\


# 获取本地视频地址
def chart_get_videos(match_id):
    if match_id:
        root_path = "F:\\media\\"  # lynn 待修改
        path = match_id + '\\'
        video_path = []
        try:
            video = os.listdir(root_path + "videos\\" + path)
            for vid in video:
                single_video = {
                    'path': str(root_path + "videos\\" + path + vid),
                    'name': str(vid)
                }
                video_path.append(single_video)
            info = {
                'successful': True,
                'data': [
                    video_path
                ],
                'code': ERROR_CODE_OPERATION_SUCCESS,
                'message': '已获取信息'
            }
        except:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '未找到比赛'
            }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
        else:
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
    else:
        info = {
            'successful': False,
            'data': None,
            'code': ERROR_CODE_OPERATION_FAILED,
            'message': '未找到比赛'
        }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})


# 获取本地音频地址
def chart_get_voices(match_id):
    if match_id:
        root_path = "E:\\proj\\chuanmei_news-kong_dev\\chuanmei_news-kong_dev\\news_server\\media\\"
        path = match_id + '\\'
        voice_path = []
        try:
            voice = os.listdir(root_path + "voices\\" + path)
            for vid in voice:
                if vid.endswith('.mp3') and "chart" not in vid:
                    single_voice = {
                        'path': str(root_path + "voices\\" + path + vid),
                        'name': str(vid)
                    }
                    voice_path.append(single_voice)
            info = {
                'successful': True,
                'data': [
                    voice_path
                ],
                'code': ERROR_CODE_OPERATION_SUCCESS,
                'message': '已获取信息'
            }
        except:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '未找到比赛'
            }
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
        else:
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
    else:
        info = {
            'successful': False,
            'data': None,
            'code': ERROR_CODE_OPERATION_FAILED,
            'message': '未找到比赛'
        }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})


# 获取本地文章地址（已弃用）
def chart_get_article(match_id):
    if match_id:
        file_path = "F:\\media\\article\\" + match_id + "\\" + match_id + ".txt"
        print(file_path)
        try:
            with open(file_path, 'r+') as f:
                info = {
                    'successful': True,
                    'data': str(f.read().strip('\n')),
                    'code': ERROR_CODE_OPERATION_SUCCESS,
                    'message': '已获取信息'
                }
                f.close()
        except:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '未找到文件'
            }
            print("ERROR")
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
        else:
            return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
    else:
        info = {
            'successful': False,
            'data': None,
            'code': ERROR_CODE_OPERATION_FAILED,
            'message': '未找到文章'
        }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})


# 语音生成
def chart_make_TtoV(Text, match_id):
    if match_id and Text:
        vpath = []
        text = Text.split("\n")
        i = 1
        for t in text:
            vpath.append(TtoV.Text_to_Voice_v(t, match_id, i))
            i += 1
        if vpath:
            info = {
                'successful': True,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '转换成功'
            }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '转换失败'
            }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
    else:
        info = {
            'successful': False,
            'data': None,
            'code': ERROR_CODE_OPERATION_FAILED,
            'message': '未获得信息'
        }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})


# lynn 增加ID转换
def match_to_data(match_id):
    return match_id


# 生成图表的文字转语音结果并返回值 match_id 大于158493则没有stat-nba数据了
def chart_make_chart_TtoV(type, name, match_id):
    # 用一个假的值保证函数可用
    chart_voice = {
        'path': '',
        'duration': 0
    }
    if int(match_id) < 158490:
        match_data_id = ID_Translator(match_id)
    else:
        match_data_id = match_id
    text = makeChartText.makeTextbyChartType(Get_ChartDetailInfo(type, match_data_id, name, chart_voice))
    duration = 0
    for t in text:
        duration += 0.7
    print(text)
    try:
        path = TtoV.Text_to_Voice(text, match_id)  # 保存的时候还用原来的hupu id
        if path:
            data = {
                'path': path,
                'duration': duration
            }
            info = {
                'successful': True,
                'data': data,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '转换成功'
            }
        else:
            info = {
                'successful': False,
                'data': None,
                'code': ERROR_CODE_OPERATION_FAILED,
                'message': '未获得信息'
            }
    except:
        info = {
            'successful': False,
            'data': None,
            'code': ERROR_CODE_OPERATION_FAILED,
            'message': '转换失败'
        }
    else:
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})


# 使用 mongoDB 进行图表操作——————————————————————————————————————————————————————————————————————————————————————
# 获取比赛是否存在
def Find_match(match_id):
    nba_id = ID_Translator(match_id)
    matchs = collection1.find({"url": ('http://stat-nba.com/game/' + str(nba_id) + '.html')})
    if matchs[0]:
        return nba_id
    else:
        return False


# 比赛基本信息图
def Get_basic_match(chart_type, match_id, chart_voice):
    path_sys = 'media\\'
    value = {"url": ('http://stat-nba.com/game/' + str(match_id) + '.html')}
    matchs = collection1.find(value)
    if matchs and matchs.count():
        match = matchs[0]
        team1 = {
            'name': match['team1Info'][1],
            'history': match['team1Info'][2],
            'logo': match['team1Info'][0],
            'score': match['team1Score'],
            'final_score': match['team1Home'][0],
            'home': match['team1Home'][1],
            'color': "#08d9d6"
        }
        team2 = {
            'name': match['team2Info'][1],
            'history': match['team2Info'][2],
            'logo': match['team2Info'][0],
            'score': match['team2Score'],
            'final_score': match['team2Home'][0],
            'home': match['team2Home'][1],
            'color': "#ff2e63"
        }
        description = {
            'name': "队伍名称",
            'history': "赛前成绩",
            'logo': "队伍图标",
            'score': "各节得分情况",
            'final_score': "最终比分",
            'home': "场次",
            'color': "图表颜色"
        }
        chart = {
            'name': "比赛基本信息图",
            'chart_type': chart_type,
            'chart_voice': [
                path_sys + chart_voice['path']
            ],
            'duration': chart_voice['duration'],
            'data': {
                'team1': team1,
                'team2': team2
            },
            'description': description
        }
        return chart


# 球队基础数据图
def Get_team_match(match_id, chart_voice):
    path_sys = 'media\\'
    value = {"url": ('http://stat-nba.com/game/' + str(match_id) + '.html')}
    matchs = collection1.find(value)
    if matchs and matchs.count():
        match = matchs[0]
        # 首先进行排序整理，这里排序的 Key 需要再检查
        match['team1Detail'].sort(key=lambda x: x[2], reverse=True)
        team1_Max_score = {
            'member': match['team1Detail'][0][0],
            'score': match['team1Detail'][0][2]
        }
        match['team1Detail'].sort(key=lambda x: x[13], reverse=True)
        team1_Max_backboard = {
            'member': match['team1Detail'][0][0],
            'score': match['team1Detail'][0][2]
        }
        match['team1Detail'].sort(key=lambda x: x[16], reverse=True)
        team1_Max_assisting = {
            'member': match['team1Detail'][0][0],
            'score': match['team1Detail'][0][2]
        }
        team1 = {
            'name': match['team1Info'][1],
            'shoot': match['team1Summary'][0][1],
            'tpt': match['team1Summary'][0][4],
            'penalty': match['team1Summary'][0][7],
            'backboard': match['team1Summary'][0][11],
            'assisting': match['team1Summary'][0][14],
            'steals': match['team1Summary'][0][15],
            'block_shots': match['team1Summary'][0][16],
            'miss': match['team1Summary'][0][17],
            'foul': match['team1Summary'][0][18],
            'Max_score': team1_Max_score,
            'Max_backboard': team1_Max_backboard,
            'Max_assisting': team1_Max_assisting,
            'color': "#08d9d6"
        }
        match['team2Detail'].sort(key=lambda x: x[2], reverse=True)
        team2_Max_score = {
            'member': match['team2Detail'][0][0],
            'score': match['team2Detail'][0][2]
        }
        match['team2Detail'].sort(key=lambda x: x[13], reverse=True)
        team2_Max_backboard = {
            'member': match['team2Detail'][0][0],
            'score': match['team2Detail'][0][2]
        }
        match['team2Detail'].sort(key=lambda x: x[16], reverse=True)
        team2_Max_assisting = {
            'member': match['team2Detail'][0][0],
            'score': match['team2Detail'][0][2]
        }
        team2 = {
            'name': match['team2Info'][1],
            'shoot': match['team2Summary'][0][1],
            'tpt': match['team2Summary'][0][4],
            'penalty': match['team2Summary'][0][7],
            'backboard': match['team2Summary'][0][11],
            'assisting': match['team2Summary'][0][14],
            'steals': match['team2Summary'][0][15],
            'block_shots': match['team2Summary'][0][16],
            'miss': match['team2Summary'][0][17],
            'foul': match['team2Summary'][0][18],
            'Max_score': team2_Max_score,
            'Max_backboard': team2_Max_backboard,
            'Max_assisting': team2_Max_assisting,
            'color': "#ff2e63"
        }
        description = {
            'name': "队伍名称",
            'shoot': "投篮",
            'tpt': "三分",
            'penalty': "罚球",
            'backboard': "篮板",
            'assisting': "助攻",
            'steals': "抢断",
            'block_shots': "盖帽",
            'miss': "失误",
            'foul': "犯规",
            'Max_score': "最佳得分",
            'Max_backboard': "最佳篮板",
            'Max_assisting': "最佳助攻",
            'color': "图表颜色"
        }
        chart = {
            'name': "球队基础数据图",
            'chart_type': "team_match",
            'chart_voice': [
                path_sys + chart_voice['path']
            ],
            'duration': chart_voice['duration'],
            'data': {
                'team1': team1,
                'team2': team2
            },
            'description': description
        }
        return chart


# 球员基础数据图
def Get_basic_player(match_id, chart_voice):
    path_sys = 'media\\'
    value = {"url": ('http://stat-nba.com/game/' + str(match_id) + '.html')}
    matchs = collection1.find(value)
    if matchs and matchs.count():
        match = matchs[0]
        team1 = {
            'name': match['team1Info'][1],
            'value': match['team1Detail']
        }
        team2 = {
            'name': match['team2Info'][1],
            'value': match['team2Detail']
        }
        description = {
            'header': "表头信息",
            'name': "队伍名称",
            'value': "对应表头的数据"
        }
        chart = {
            'name': "球员基础数据图",
            'chart_type': "basic_player",
            'chart_voice': [
                path_sys + chart_voice['path']
            ],
            'duration': chart_voice['duration'],
            'data': {
                'team1': team1,
                'team2': team2
            },
            'description': description
        }
        return chart


# 球员场均雷达图
def Get_avg_player(match_id, player, chart_voice):
    path_sys = 'media\\'
    value = {"url": ('http://stat-nba.com/game/' + str(match_id) + '.html')}
    matchs = collection1.find(value)
    if matchs and matchs.count():
        match = matchs[0]
        total_team_detail = match['team1Detail'] + match['team2Detail']
        for play in total_team_detail:
            if player in play[0]:
                # 查找球员数据
                avgPlayer = collection2.find({"cnName": player})
                if avgPlayer and avgPlayer.count():
                    avg = avgPlayer[0]
                    # 查找球员数据
                    data = {
                        'name_cn': play[0],
                        'name_eng': play[0],
                        'img': match['team1Info'][0],
                        'shoot': play[3],
                        'backboard': play[13],
                        'assisting': play[16],
                        'steals': play[17],
                        'block_shots': play[18],
                        'miss': play[19],
                        'foul': play[20],
                        'score': play[21],
                        # 这里没有修复数据 #lynn 修复
                        'shoot_avg': avg['seasonAvg'][5],
                        'backboard_avg': avg['seasonAvg'][14],
                        'assisting_avg': avg['seasonAvg'][17],
                        'steals_avg': avg['seasonAvg'][18],
                        'block_shots_avg': avg['seasonAvg'][19],
                        'miss_avg': avg['seasonAvg'][20],
                        'foul_avg': avg['seasonAvg'][21],
                        'score_avg': avg['seasonAvg'][22],
                    }
                else:
                    data = {
                        'name_cn': play[0],
                        'name_eng': play[0],
                        'img': match['team1Info'][0],
                        'shoot': play[3],
                        'backboard': play[13],
                        'assisting': play[16],
                        'steals': play[17],
                        'block_shots': play[18],
                        'miss': play[19],
                        'foul': play[20],
                        'score': play[21],
                        # 这里没有修复数据
                        'shoot_avg': str(round(random.uniform(0.8, 1.1) * float(play[3].strip('%')))) + '%',
                        'backboard_avg': str(round(random.uniform(0, 1.5) * float(play[13]))),
                        'assisting_avg': str(round(random.uniform(0, 1.5) * float(play[16]))),
                        'steals_avg': str(round(random.uniform(0, 1.5) * float(play[17]))),
                        'block_shots_avg': str(round(random.uniform(0, 1.5) * float(play[18]))),
                        'miss_avg': str(round(random.uniform(0, 1.5) * float(play[19]))),
                        'foul_avg': str(round(random.uniform(0, 1.5) * float(play[20]))),
                        'score_avg': str(round(random.uniform(0, 1.5) * float(play[21]))),
                    }
                description = {
                    'name_cn': "球员中文名字",
                    'name_eng': "球员英文名字",
                    'img': "球员图片",
                    'shoot': "投篮",
                    'backboard': "篮板",
                    'assisting': "助攻",
                    'steals': "抢断",
                    'block_shots': "盖帽",
                    'miss': "失误",
                    'foul': "犯规",
                    'score': "得分",
                    'shoot_avg': "生涯平均投篮",
                    'backboard_avg': "生涯平均篮板",
                    'assisting_avg': "生涯平均助攻",
                    'steals_avg': "生涯平均抢断",
                    'block_shots_avg': "生涯平均盖帽",
                    'miss_avg': "生涯平均失误",
                    'foul_avg': "生涯平均犯规",
                    'score_avg': "生涯平均得分"
                }
                chart = {
                    'name': "球员场均雷达图",
                    'chart_type': "avg_player",
                    'chart_voice': [
                        path_sys + chart_voice['path']
                    ],
                    'duration': chart_voice['duration'],
                    'data': data,
                    'description': description
                }
                return chart


def Get_score_rose(match_id, player, chart_voice):
    path_sys = 'media\\'
    value = {"url": ('http://stat-nba.com/game/' + str(match_id) + '.html')}
    matchs = collection1.find(value)
    chart = {}
    if matchs and matchs.count():
        match = matchs[0]
        total_team_detail = match['team1Detail'] + match['team2Detail']
        for play in total_team_detail:
            if player in play[0]:
                data = {
                    'three_points': int(play[7]) * 3,
                    'second_points': int(play[21]) - (int(play[7]) * 3) - int(play[10]),
                    'penalty_shot': int(play[10])
                }
                description = {
                    "three_points": "三分",
                    "second_points": "二分",
                    "penalty_shot": "罚球"
                }
                chart = {
                    'name': play[0],
                    'chart_type': "score_rose",
                    'chart_voice': [
                        path_sys + chart_voice['path']
                    ],
                    'duration': chart_voice['duration'],
                    'data': data,
                    'description': description
                }
                return chart
    return chart


##多个球员play list
def Get_player_data_parallel(match_id, player, chart_voice):
    path_sys = 'media\\'
    value = {"url": ('http://stat-nba.com/game/' + str(match_id) + '.html')}
    matchs = collection1.find(value)
    chart = {}
    if matchs and matchs.count():
        match = matchs[0]
        total_team_detail = match['team1Detail'] + match['team2Detail']
        data = []
        for p in eval(player):
            temp_data = {}
            for play in total_team_detail:
                if p in play[0]:
                    temp_data = {
                        "name": p,
                        "backboard": play[13],
                        "assisting": play[16],
                        "steals": play[17],
                        "block_shots": play[18],
                        "miss": play[19],
                        "foul": play[20],
                        "score": play[21]
                    }
                    data.append(temp_data)
        description = {
            "name": "姓名",
            "backboard": "篮板",
            "assisting": "助攻",
            "steals": "抢断",
            "block_shots": "盖帽",
            "miss": "失误",
            "foul": "犯规",
            "score": "得分"
        }
        chart = {
            'name': '球员数据',
            'chart_type': 'player_data_parallel',
            'chart_voice': [
                path_sys + chart_voice['path']
            ],
            'duration': chart_voice['duration'],
            'data': data,
            'description': description
        }
        return chart
    return chart


##多个球员play list
def Get_player_data_stack(match_id, player, chart_voice):
    path_sys = 'media\\'
    value = {"url": ('http://stat-nba.com/game/' + str(match_id) + '.html')}
    matchs = collection1.find(value)
    chart = {}
    if matchs and matchs.count():
        match = matchs[0]
        total_team_detail = match['team1Detail'] + match['team2Detail']
        data = []
        for p in eval(player):
            temp_data = {}
            for play in total_team_detail:
                if p in play[0]:
                    temp_data = {
                        "name": p,
                        "backboard": play[13],
                        "assisting": play[16],
                        "steals": play[17],
                        "block_shots": play[18],
                        "miss": play[19],
                        "foul": play[20],
                        "score": play[21]
                    }
                    data.append(temp_data)
        description = {
            "name": "姓名",
            "backboard": "篮板",
            "assisting": "助攻",
            "steals": "抢断",
            "block_shots": "盖帽",
            "miss": "失误",
            "foul": "犯规",
            "score": "得分"
        }
        chart = {
            'name': '球员数据',
            'chart_type': 'player_data_stack',
            'chart_voice': [
                path_sys + chart_voice['path']
            ],
            'duration': chart_voice['duration'],
            'data': data,
            'description': description
        }
        return chart
    return chart


##多个球员play list
def Get_player_data_polar(match_id, player, chart_voice):
    path_sys = 'media\\'
    value = {"url": ('http://stat-nba.com/game/' + str(match_id) + '.html')}
    matchs = collection1.find(value)
    chart = {}
    if matchs and matchs.count():
        match = matchs[0]
        total_team_detail = match['team1Detail'] + match['team2Detail']
        data = []
        for p in eval(player):
            temp_data = {}
            for play in total_team_detail:
                if p in play[0]:
                    temp_data = {
                        "name": p,
                        "backboard": play[13],
                        "assisting": play[16],
                        "steals": play[17],
                        "block_shots": play[18],
                        "miss": play[19],
                        "foul": play[20],
                        "score": play[21]
                    }
                    data.append(temp_data)
        description = {
            "name": "姓名",
            "backboard": "篮板",
            "assisting": "助攻",
            "steals": "抢断",
            "block_shots": "盖帽",
            "miss": "失误",
            "foul": "犯规",
            "score": "得分"
        }
        chart = {
            'name': '球员数据',
            'chart_type': 'player_data_polar',
            'chart_voice': [
                path_sys + chart_voice['path']
            ],
            'duration': chart_voice['duration'],
            'data': data,
            'description': description
        }
        return chart
    return chart


# 搜索是否存在历史
def Search_match_id(match_id):
    matchs = collection1.find({"url": {'$regex': ('/' + str(match_id) + '.html')}})
    if matchs and matchs.count():
        match = matchs[0]
        players = []
        team1 = match['team1Detail']

        for t1 in team1:
            if len(t1) == 22 and collection2.find({"cnName": t1[0]}).count():
                players.append({
                    'name': t1[0],
                    'type': "basic_player"
                })
        team2 = match['team2Detail']
        for t2 in team2:
            if len(t2) == 22 and collection2.find({"cnName": t2[0]}).count():
                players.append({
                    'name': t2[0],
                    'type': "basic_player"
                })
        print(players)
        info = {
            'successful': True,
            'data': players,
            'code': ERROR_CODE_OPERATION_SUCCESS,
            'message': '已找到比赛'
        }
    else:
        info = {
            'successful': False,
            'data': None,
            'code': ERROR_CODE_OPERATION_SUCCESS,
            'message': '不存在的比赛'
        }
    return JsonResponse(info, json_dumps_params={'ensure_ascii': False})


# 使用 mongoDB 进行图表操作——————————————————————————————————————————————————————————————————————————————————————

def Get_ChartDetailInfo(chart_type, match_id, player, chart_voice):
    if chart_type == 'basic_match_light' or chart_type == 'basic_match_dark':
        return Get_basic_match(chart_type, match_id, chart_voice)
    elif chart_type == 'team_match':
        return Get_team_match(match_id, chart_voice)
    elif chart_type == 'basic_player': ###
        return Get_basic_player(match_id, chart_voice)
    elif chart_type == 'avg_player':
        return Get_avg_player(match_id, player, chart_voice)
    elif chart_type == 'score_rose':
        return Get_score_rose(match_id, player, chart_voice)
    elif chart_type == 'player_data_parallel':
        return Get_player_data_parallel(match_id, player, chart_voice)
    elif chart_type == 'player_data_stack':
        return Get_player_data_stack(match_id, player, chart_voice)
    elif chart_type == 'player_data_polar':
        return Get_player_data_polar(match_id, player, chart_voice)


# 本地 ID 转换
def Transform_id(match_id):
    return match_id


# 按指令组装最终图表 lynn这里组装格式问题未处理
def Get_order(match_id, chart_arr, media_arr):
    root_path = "E:\\proj\\chuanmei_news-kong_dev\\chuanmei_news-kong_dev\\news_server"
    path_sys = 'media\\'
    chart = []
    videos = []
    voices = []
    background = []
    match_nba_id = ID_Translator(match_id)
    # 获取 chart 路径

    chart.append(Get_ChartDetailInfo(chart_arr[0], match_nba_id, chart_arr[1], media_arr['chart_voice']))

    for one_video in media_arr["video"]:
        videos.append(path_sys + "videos\\" + match_id + "\\" + one_video)
    for one_voice in media_arr["voice"]:
        if match_id in one_voice['name']:
            voices.append(path_sys + "voices\\" + match_id + "\\" + one_voice['name'])
    for one_voice in media_arr["bgm"]:  # lynn 原media_arr['voice']
        # if 'bgm' in str(one_voice): #lynn
        background.append(path_sys + "bgm\\" + one_voice)

    data = {
        'timestamp': str(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))),
        'gameid': match_id,
        'user': "admin",
        'news_type': "sport",
        'media': {
            'video_path': videos,
            'voice_path': voices,
            'background': background
        },
        'root_path': root_path,
        'chart': chart
    }
    print(data)
    return data


def chart_confirmission(match_id):
    url = server_path + 'status?id=' + match_id
    ans = requests.get(url)  # 返回字节形式
    return json.load(ans.text)


def add_mission(match_id, chart_arr, media_arr):
    url = server_path + 'submit'
    data = Get_order(match_id, chart_arr, media_arr)

    body = {
        "name": match_id,
        "data": json.dumps(data)
    }

    ans = requests.post(url, body)
    res = json.loads(ans.text)
    print(res)
    if res["message"] == "递交成功":
        TChart.objects.create(match_id=match_id, state="运行", chart_id=res["result"], path="")
        info = {
            'successful': True,
            'data': ans.text,
            'code': ERROR_CODE_OPERATION_FAILED,
            'message': res["message"]
        }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})
    else:
        info = {
            'successful': False,
            'data': ans.text,
            'code': ERROR_CODE_OPERATION_FAILED,
            'message': res["message"]
        }
        return JsonResponse(info, json_dumps_params={'ensure_ascii': False})


# 调用接口获得任务结果
def get_mission_result(match_id):
    id = TChart.objects.filter(match_id=match_id)[0].chart_id
    url = server_path + 'result/?id=' + id
    ans = requests.get(url)
    res = json.loads(ans.text)
    return res


# 获得任务结果
def get_mission_result_local(match_id):
    info = TChart.objects.filter(match_id=match_id)
    if not info:
        # 如果表里没有
        info = "未生成"
        return info
    else:
        # 如果表里有取回表里的值
        info = info[0].state

    if info == "运行":
        # 如果表里在运行
        info = get_mission_result(match_id)
        single_list = TChart.objects.filter(match_id=match_id)[0]
        if not info["result"]:
            return "运行"
        else:
            single_list.path = info["result"]
            single_list.state = info["message"]
            single_list.save()
        return "成功"
    return info


def get_mission_result_video(match_id):
    info = TChart.objects.filter(match_id=match_id)
    if not info:
        return None
    else:
        info = str(info[0].path)
        info = info.split("\\")
        info = info[len(info) - 1]
        return "../output/" + info


# 生成测试接口
def Get_order_test(match_id):
    data2 = {
        'timestamp': '2021-06-08 01:29:25',
        'gameid': '43337',
        'user': 'admin',
        'news_type': 'sport',
        'media': {
            'video_path': ['\\media\\155832-1.mp4'],
            'voice_path': ['\\media\\voices\\43337\\43337_chart_1.mp3'],
            'background': ['']
        },
        'root_path': '',
        'chart': [{
            'name': '比赛基本信息图',
            'chart_type': 'basic_match_light',
            'chart_voice': ['\\media\\voices\\43337\\43337_chart_1.mp3'],
            'duration': 7.5,
            'data': {'team1': {'name': '密尔沃基雄鹿', 'history': '(赛前战绩 37胜13负)',
                               'logo': 'http://stat-nba.com//image/teamImage/MIL.gif',
                               'score': ['38', '35', '27', '31'], 'final_score': '131', 'home': '客场',
                               'color': '#08d9d6'}, 'team2': {'name': '华盛顿奇才', 'history': '(赛前战绩 22胜29负)',
                                                              'logo': 'http://stat-nba.com//image/teamImage/WAS.gif',
                                                              'score': ['26', '24', '34', '31'], 'final_score': '115',
                                                              'home': '主场', 'color': '#08d9d6'}},
            'description': {'name': '队伍名称', 'history': '赛前成绩', 'logo': '队伍图标', 'score': '各节得分情况', 'final_score': '最终比分',
                            'home': '场次', 'color': '图表颜色'}
        }]
    }

    body = {
        "name": match_id,
        "data": json.dumps(data2)
    }
    return body


# 数据库转换 ID
def ID_Translator(hupu_id):
    value = {"HUPU": hupu_id}
    matchs = collection3.find(value)
    match = None
    if matchs:
        match = matchs[0]
        match = match["NBA"]
    return match
